package huachenxing.mimi520.tools
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.Dictionary;
	
	import mx.utils.StringUtil;

	dynamic public class ConfigFile extends Dictionary
	{
		
		private var _name:String;
		
		public function ConfigFile(name:String)
		{
			_name = name;
		}
		
		public function read():void
		{
			var configFolder:File = File.applicationDirectory.resolvePath("configs");
			if(configFolder.exists)
			{
				var configFile:File = configFolder.resolvePath(_name + ".conf");
				if(configFile.exists)
				{
					var fileStream:FileStream = new FileStream();
					fileStream.open(configFile, FileMode.READ);
					var configContent:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
					fileStream.close();
					
					var contentArray:Array = configContent.split(";");
					for each(var line:String in contentArray)
					{
						line = StringUtil.trim(line);
						if(line.length == 0) continue;
						if(line.charAt(0) == "#") continue;
						var lineArray:Array = line.split("=", 2);
						var key:String = StringUtil.trim(lineArray[0]);
						var value:String = StringUtil.trim(lineArray[1]);
						this[key] = value;
					}
				}
			}
		}
		
		public function write():void
		{
			var contentArray:Array = [];
			for(var key:String in this) {
				var value:String = this[key];
				var line:String = key + "=" + value + ";";
				contentArray.push(line);
			}
			var configContent:String = contentArray.join("\r\n");
			
			var configFolder:File = new File(File.applicationDirectory.nativePath).resolvePath("configs");
			if(!configFolder.exists) configFolder.createDirectory();
			var configFile:File = configFolder.resolvePath(_name + ".conf");
			var fileStream:FileStream = new FileStream();
			fileStream.open(configFile, FileMode.WRITE);
			fileStream.writeUTFBytes(configContent);
			fileStream.close();
		}
	}
}